package com.it.sun.easychat.common.jdbctypehandler;

import cn.hutool.core.util.ObjectUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author sunmannian
 * @ClassName com.it.sun.easychat.common.jdbctypehandler.ListTypeHandler
 * @Date 2020/5/27 17:19
 * @Version V1.0
 * Description  <请输入一句话描述该类功能>
 * Copyright (C) 北京中电兴发科技有限公司  since 2020/5/27
 */
@MappedTypes({List.class})
@Component
public class ListTypeHandler implements TypeHandler<List<? extends Object>> {

    @Override
    public void setParameter(PreparedStatement ps, int i, List<?> parameter, JdbcType jdbcType) throws SQLException {
        ps.setBytes(i, ObjectUtil.serialize(parameter));
    }

    @Override
    public List<? extends Object> getResult(ResultSet rs, String columnName) throws SQLException {
        byte[] bys = rs.getBytes(columnName);
        if (null != bys) {
            return ObjectUtil.deserialize(bys);
        }
        return null;
    }

    @Override
    public List<? extends Object> getResult(ResultSet rs, int columnIndex) throws SQLException {
        byte[] bys = rs.getBytes(columnIndex);
        if (null != bys) {
            return ObjectUtil.deserialize(bys);
        }
        return null;
    }

    @Override
    public List<? extends Object> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        byte[] bys = cs.getBytes(columnIndex);
        if (null != bys) {
            return ObjectUtil.deserialize(bys);
        }
        return null;
    }
}
